#include <Arduino.h>
#include "com/communication.h"
#include "message.h"
#include "protocol.h"

 // 7 on slave hardware
#define BUTTON 3
#define LED 5


volatile bool button_pressed = false;
extern volatile bool received_msg;

void pair_with_master();

int main(void) {
	init();

	setup();

	for (;;)
		loop();

	return 0;
}




void setup() {
	// Button input pin
	pinMode(BUTTON, INPUT);
	digitalWrite(BUTTON, HIGH);
	// LED output pin
	//pinMode(LED, OUTPUT);
	//digitalWrite(LED, HIGH); // LED off

	Serial.begin(9600);
	Serial.println("I\'m a slave!");

	com_activate_debug();
	com_init_slave();

	delay(500);

	bool paired = false;
	while(!paired) {
		Serial.println("Waiting for button");
		while(digitalRead(BUTTON) != LOW) // while button not pressed
			delay(10);
		delay(100);
		if(digitalRead(BUTTON) == LOW) // Button must be pressed 100ms
			paired = com_pair_with_master();
	}
	Serial.println("Successfully paired");
}

void loop() {
	// Tell master the sensor type and value type
	message val_msg_type = message(1, BRIGHTNESS, INT16, 1);
	com_send_msg_to_master(val_msg_type);

	// Read value and send it to master
	int val = analogRead(A0);
	message val_msg = message(1, MSG_INT16);
	val_msg.setValue(val);
	com_send_msg_to_master(val_msg);

	delay(500);
}
